package com.xhapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xhapi.config.XfXhConfig;
import com.xhapi.pojo.dto.PPTCreatorDTO;
import com.xhapi.pojo.entity.CreateResponse;
import com.xhapi.pojo.entity.ProgressResponse;
import com.xhapi.service.PPTCreatorService;
import com.xhapi.utils.pptCreatorUtils.ApiAuthAlgorithm;
import com.xhapi.utils.pptCreatorUtils.ApiClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
@Slf4j
@Service
@RequiredArgsConstructor
public class PPTCreatorServiceImpl implements PPTCreatorService {
    private final XfXhConfig xfXhConfig;
    @Override
    public String createPPTByInput(PPTCreatorDTO dto) throws IOException, InterruptedException {
        // 处理异常信息
        if(StringUtils.isEmpty(dto.getQuery())){
            return "大哥你写点东西呀，啥都没有我怎么给你生成PPT";
        }
        if(StringUtils.isEmpty(dto.getCreate_model())){
            dto.setCreate_model("auto");
        }
        if(StringUtils.isEmpty(dto.getTheme())){
            dto.setTheme("auto");
        }
        if(StringUtils.isEmpty(dto.getAuthor())){
            dto.setTheme("烫烫烫与锟斤拷团队");
        }

        String appId = xfXhConfig.getAppId();
        String secret = xfXhConfig.getApiSecret();
        long timestamp = System.currentTimeMillis()/1000;
        String ts = String.valueOf(timestamp);
        // 获得鉴权信息
        ApiAuthAlgorithm auth = new ApiAuthAlgorithm();
        String signature = auth.getSignature(appId, secret, timestamp);
        log.info("鉴权信息为：{}",signature);

        // 建立链接
        ApiClient client = new ApiClient("https://zwapi.xfyun.cn");
        // 查询PPT模板信息
        String templateResult = client.getTemplateList(appId, ts, signature);
        log.info("PPT模板信息为：{}",templateResult);

        // 发送生成PPT请求
        String resp = client.createPPT(appId, ts, signature,dto.getQuery(),dto.getCreate_model(),
                dto.getTheme(),dto.getAuthor());
        log.info("发送了生成PPT请求:{}",resp);
        CreateResponse response = JSON.parseObject(resp, CreateResponse.class);

        int progress = 0;
        ProgressResponse progressResponse;
        while (progress < 100) {
            String progressResult = client.checkProgress(appId, ts, signature, response.getData().getSid());
            progressResponse = JSON.parseObject(progressResult, ProgressResponse.class);
            progress = progressResponse.getData().getProcess();
            System.out.println(progressResult);
            if (progress < 100) {
                Thread.sleep(5000); // 暂停2秒
            }
            else {
                return progressResponse.getData().getPptUrl();
            }
        }
        return "error!";
    }
}
